package com.cn.yunhe.rentcars.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller  
public class FileUploadController {  
   
	@Autowired
	private Environment env;
	  
    @RequestMapping(value="/uploadFile", method=RequestMethod.POST)  
    @ResponseBody
    public  Map<String,String> uploadFile( 
            @RequestParam("uploadfile") MultipartFile file){ 
    	Map<String,String> map = new HashMap<String,String>();
        if (!file.isEmpty()) {  
            try {  
              
                // Get the filename and build the local file path
                //上传文件的名字
            	String  name= file.getOriginalFilename();                
                //上传文件保存的名字=UUID+后缀
            	String filename = UUID.randomUUID().toString()+name.substring(name.lastIndexOf(".")-1);           
                String directory = env.getProperty("jkd.paths.uploadedFiles");
        
                String filepath = Paths.get(directory, filename).toString();
                System.out.println(filename);
                // Save the file locally
                BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(filepath)));
                stream.write(file.getBytes());
                stream.close();         
                
                
            	
            		map.put("flag",filename);
            		return map;    
            } catch (Exception e) {  
               map.put("flag", "上传失败"); 
            	return map;  
            }  
        } else {  
        	map.put("flag","图片错误");
    		return map; 
        }  
    }  
   
} 